import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/stores/user'

const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录', requiresAuth: false }
  },
  {
    path: '/',
    component: () => import('@/layout/Layout.vue'),
    redirect: '/dashboard',
    meta: { requiresAuth: true },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '主控台', icon: 'Odometer' }
      },
      {
        path: 'work',
        name: 'Work',
        meta: { title: '我的工作', icon: 'Briefcase' },
        children: [
          {
            path: 'applications',
            name: 'Applications',
            component: () => import('@/views/work/Applications.vue'),
            meta: { title: '我的申请', icon: 'Document' }
          },
          {
            path: 'approvals',
            name: 'Approvals',
            component: () => import('@/views/work/Approvals.vue'),
            meta: { title: '待我审批', icon: 'Check' }
          },
          {
            path: 'initiated',
            name: 'Initiated',
            component: () => import('@/views/work/Initiated.vue'),
            meta: { title: '我发起的', icon: 'List' }
          }
        ]
      },
      
      {
        path: 'jsa',
        name: 'JSA',
        meta: { title: 'JSA管理', icon: 'Warning' },
        children: [
          {
            path: 'list',
            name: 'JSAList',
            component: () => import('@/views/jsa/List.vue'),
            meta: { title: 'JSA列表', icon: 'List' }
          },
          {
            path: 'create',
            name: 'JSACreate',
            component: () => import('@/views/jsa/Create.vue'),
            meta: { title: 'JSA创建', icon: 'Edit', hidden: true }
          },
          {
            path: 'confirm/:id',
            name: 'JSAConfirm',
            component: () => import('@/views/jsa/Confirm.vue'),
            meta: { title: 'JSA确认', icon: 'Check', hidden: true }
          },
          {
            path: 'template',
            name: 'JSATemplate',
            component: () => import('@/views/jsa/TemplateList.vue'),
            meta: { title: 'JSA模板管理', icon: 'Document' }
          }
        ]
      },
      {
        path: 'permit',
        name: 'Permit',
        meta: { title: '作业许可管理', icon: 'Lock' },
        children: [
          {
            path: 'list',
            name: 'PermitList',
            component: () => import('@/views/permit/List.vue'),
            meta: { title: '许可证列表', icon: 'List' }
          },
          {
            path: 'apply',
            name: 'PermitApply',
            component: () => import('@/views/permit/Apply.vue'),
            meta: { title: '许可证申请', icon: 'Plus', hidden: true }
          },
          {
            path: 'approval',
            name: 'PermitApproval',
            component: () => import('@/views/permit/Approval.vue'),
            meta: { title: '许可证审批', icon: 'Check' }
          },
          {
            path: 'execution',
            name: 'PermitExecution',
            component: () => import('@/views/permit/Execution.vue'),
            meta: { title: '执行中作业', icon: 'Operation' }
          },
          {
            path: 'vehicle-records',
            name: 'VehicleRecords',
            component: () => import('@/views/permit/VehicleRecords.vue'),
            meta: { title: '运输车记录', icon: 'Truck' }
          }
        ]
      },
      {
        path: 'points',
        name: 'Points',
        meta: { title: '积分管理', icon: 'Trophy' },
        children: [
          {
            path: 'record',
            name: 'PointsRecord',
            component: () => import('@/views/points/Record.vue'),
            meta: { title: '积分记录与登记', icon: 'Edit' }
          },
          {
            path: 'approval',
            name: 'PointsApproval',
            component: () => import('@/views/points/Approval.vue'),
            meta: { title: '积分流程审批', icon: 'Check' }
          },
          {
            path: 'ledger',
            name: 'PointsLedger',
            component: () => import('@/views/points/Ledger.vue'),
            meta: { title: '积分台账与统计', icon: 'DataAnalysis' }
          }
        ]
      },

      {
        path: 'statistics',
        name: 'Statistics',
        component: () => import('@/views/Statistics.vue'),
        meta: { title: '统计看板', icon: 'DataAnalysis', roles: ['admin', 'manager'] }
      },
      {
        path: 'file',
        name: 'FileManagement',
        component: () => import('@/views/system/FileManagement.vue'),
        meta: { title: '文件管理', icon: 'Folder' }
      },
      {
        path: 'display',
        name: 'Display',
        component: () => import('@/views/Display.vue'),
        meta: { title: '大屏展示', icon: 'Monitor', roles: ['display'] }
      },
      {
        path: 'system',
        name: 'System',
        meta: { title: '系统管理', icon: 'Setting', roles: ['admin'] },
        children: [
          {
            path: 'user',
            name: 'User',
            component: () => import('@/views/system/User.vue'),
            meta: { title: '用户管理', icon: 'User' }
          },
          {
            path: 'role',
            name: 'Role',
            component: () => import('@/views/system/Role.vue'),
            meta: { title: '角色管理', icon: 'UserFilled' }
          },
          {
            path: 'department',
            name: 'Department',
            component: () => import('@/views/system/Department.vue'),
            meta: { title: '部门管理', icon: 'OfficeBuilding' }
          },
          {
            path: 'contractor',
            name: 'Contractor',
            component: () => import('@/views/system/Contractor.vue'),
            meta: { title: '承包商管理', icon: 'Building' }
          },
          {
            path: 'menu',
            name: 'Menu',
            component: () => import('@/views/system/Menu.vue'),
            meta: { title: '菜单管理', icon: 'Menu' }
          },
          {
            path: 'dictionary',
            name: 'Dictionary',
            component: () => import('@/views/system/Dictionary.vue'),
            meta: { title: '数据字典', icon: 'Collection' }
          }
        ]
      }
    ]
  },
  {
    path: '/display-screen',
    name: 'DisplayScreen',
    component: () => import('@/views/Display.vue'),
    meta: { title: '大屏展示', requiresAuth: false }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue'),
    meta: { title: '页面不存在' }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - Vue3 后台管理框架`
  }
  
  // 检查是否需要认证
  if (to.meta.requiresAuth !== false) {
    if (!userStore.token) {
      next('/login')
      return
    }
  }
  
  // 如果已登录且访问登录页，重定向到首页
  if (to.path === '/login' && userStore.token) {
    next('/')
    return
  }
  
  next()
})

export default router
